package cn.itcast.search.service.impl;

import cn.itcast.feign.client.ItemClient;
import cn.itcast.hmall.dto.common.PageDTO;
import cn.itcast.hmall.dto.common.ResultDTO;
import cn.itcast.hmall.dto.item.SearchItemDTO;
import cn.itcast.hmall.dto.search.SearchReqDTO;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.item.ItemDoc;
import cn.itcast.search.service.EsMapper;
import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class EsMapperImpl implements EsMapper {
    @Autowired
    private ItemClient itemClient;

    @Autowired
    private RestHighLevelClient client;

    public ResultDTO importData() {

        int count = 1;
        while (true) {
            BulkRequest request = new BulkRequest();
            SearchItemDTO searchItemDTO = new SearchItemDTO();

            searchItemDTO.setPage(count++);
            searchItemDTO.setSize(1000);

            PageDTO<Item> itemPageDTO = this.itemClient.searchByPage(searchItemDTO);

            List<Item> list = itemPageDTO.getList();

            for (Item item : list) {
                ItemDoc itemDoc = new ItemDoc(item);
                request.add(new IndexRequest("item")
                        .id(itemDoc.getId().toString())
                        .source(JSON.toJSONString(itemDoc), XContentType.JSON)
                );
            }
            try {
                client.bulk(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
                return ResultDTO.error("操作失败");
            }
            if (list.size() < 1000) return ResultDTO.ok("操作完成");
        }
    }

    @Override
    public Map<String, List<String>> filters(SearchReqDTO dto) {

        //构建请求
        SearchRequest item = new SearchRequest("item");
        SearchSourceBuilder source = item.source();

        //构建分页条件
        Integer current = null;
        if (ObjectUtils.isNotEmpty(dto.getPage())) current = dto.getPage();

        Integer size = null;
        if (ObjectUtils.isNotEmpty(dto.getSize()))
            size = dto.getSize();
        IPage<Item> itemPage = null;
        if (ObjectUtils.isEmpty(dto.getPage()) || ObjectUtils.isEmpty(dto.getSize()))
            itemPage = new Page();
        else itemPage = new Page(current, size);

        //构建查询条件
        String brand = dto.getBrand();
        String category = dto.getCategory();
        Double minPrice = dto.getMinPrice();
        Double maxPrice = dto.getMaxPrice();


        source.aggregation(AggregationBuilders.terms("brandagg").field("brand").size(20));
        source.aggregation(AggregationBuilders.terms("cateAgg").field("category").size(20));

        if (ObjectUtils.isNotEmpty(brand))
            source.query(QueryBuilders.termQuery("brand", brand));
        if (ObjectUtils.isNotEmpty(category))
            source.query(QueryBuilders.termQuery("category", category));
        if (ObjectUtils.isNotEmpty(maxPrice) && ObjectUtils.isNotEmpty(minPrice))
            source.query(QueryBuilders.rangeQuery("price").lte(maxPrice).gte(minPrice));

        //解析结果
        SearchResponse search = null;
        try {
            search = client.search(item, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        Aggregations aggregations = search.getAggregations();

        List<String> brandList = getAggByName(aggregations, "brandagg");
        List<String> cateList = getAggByName(aggregations, "cateAgg");
        Map<String, List<String>> maps = new HashMap<>();
        maps.put("category", cateList);
        maps.put("brand", brandList);

        return maps;
    }

    @Override
    public PageDTO<ItemDoc> list(SearchReqDTO dto) {

        //构建请求
        SearchRequest item = new SearchRequest("item");
        SearchSourceBuilder source = item.source();

        if (ObjectUtils.isNotEmpty(dto.getKey()))
            source.query(QueryBuilders.matchQuery("name", dto.getKey()));
        if (ObjectUtils.isNotEmpty(dto.getBrand()))
            source.query(QueryBuilders.termQuery("brand", dto.getBrand()));
        if (ObjectUtils.isNotEmpty(dto.getSize()) && ObjectUtils.isNotEmpty(dto.getPage()))
            source.from(dto.getSize() * (dto.getPage() - 1)).size(dto.getSize());
        if (!dto.getSortBy().equals("default")&&ObjectUtils.isNotEmpty(dto.getSize()))
            source.sort(dto.getSortBy());//存在重大bug，排序字段不指定会报错无法运行
        if (ObjectUtils.isNotEmpty(dto.getMaxPrice()) && ObjectUtils.isNotEmpty(dto.getMinPrice()))
            source.query(QueryBuilders.rangeQuery("price")
                    .gte(dto.getMinPrice()).lte(dto.getMaxPrice()));
        source.highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

        SearchResponse search = null;
        try {
            search = client.search(item, RequestOptions.DEFAULT);
        } catch (IOException e) {
            System.out.println(search.getSkippedShards());
            e.printStackTrace();
        }
        SearchHits hits = search.getHits();
        TotalHits total = hits.getTotalHits();
        long totalvalue = total.value;
        SearchHit[] hits1 = hits.getHits();

        List<ItemDoc> list = new ArrayList<>();
        for (SearchHit hi : hits1) {
            String sourceAsString = hi.getSourceAsString();

            Object parse = JSON.parse(sourceAsString);
            ItemDoc i = JSON.parseObject(sourceAsString, ItemDoc.class);
            Map<String, HighlightField> highlightFields = hi.getHighlightFields();
            HighlightField name = highlightFields.get("name");
            i.setName(name.toString());
            list.add(i);
        }
        return new PageDTO<ItemDoc>(totalvalue, list);
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    @Override
    public List<String> suggestionList(String key) {

        //获取请求对象
        SearchRequest item = new SearchRequest("item");
        SearchSourceBuilder source = item.source();

        source.suggest(new SuggestBuilder().addSuggestion("mysuggest",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(key)
                        .skipDuplicates(true)
                        .size(10)));

        //发起请求
        SearchResponse search = null;
        try {
            search = client.search(item, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        //解析结果
        CompletionSuggestion mysuggest = search.getSuggest().getSuggestion("mysuggest");

        List<CompletionSuggestion.Entry.Option> options = mysuggest.getOptions();

        ArrayList<String> list = new ArrayList<>();

        for (CompletionSuggestion.Entry.Option option : options) {
            String s = option.getText().toString();
            list.add(s);
        }
        return list;
    }
}
